<template>
  <view :data-theme="theme">
    <nav-bar
      :navTitle="title"
      iconColor="#000"
      :backgroundColor="backgroundColor"
      :isBackgroundColor="false"
    ></nav-bar>
    <view class="new-users copy-data tui-skeleton">
      <view class="mid" style="flex: 1; overflow: hidden">
        <scroll-view scroll-y="true">
          <view class="head borderPad">
            <view
              class="bg"
              :style="{
                'background-image': `url(https://crmed.cszhixuan.com/crmebimage/presets/user_bg.png)`,
              }"
            >
              <view class="user-card">
                <view class="user-info">
                  <!-- #ifdef MP-WEIXIN -->
                  <image
                    class="avatar tui-skeleton-rect"
                    :src="
                      userInfo.avatar
                        ? userInfo.avatar.includes('crmebimage')
                          ? 'https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/notLogged.png'
                          : userInfo.avatar
                        : userInfo.avatar
                    "
                  ></image>
                  <!-- #endif -->
                  <view class="info">
                    <view class="name col-balck" v-if="!isLogin" @tap="openAuto">
                      请点击登录
                    </view>
                    <view class="name" v-if="userInfo && uid">
                      <view
                        class="num mt10"
                        v-if="userInfo && userInfo.phone && uid"
                        @click="goEdit()"
                      >
                        <view class="num-txt fw-600">{{ userInfo.phone }}</view>
                      </view>
                    </view>
                    <view
                      class="num mt10"
                      v-if="userInfo && userInfo.phone && uid"
                      @click="goEdit()"
                    >
                      <view class="mark-txt">{{ "普通会员" }}</view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="svip-box">
              <view class="casing borRadius-19 bg-white">
                <view class="ability fw-600">推广明细</view>
                <view
                  class="harvest borRadius-19 flex bg-white justify-between w-full"
                >
                  <view
                    class="frame"
                    v-for="(el, idx) in harvestList"
                    :key="idx"
                  >
                    <view class="frameLine" v-if="idx !== 2"></view>
                    <view class="digitList flex justify-center">
                      <view class="digit dinAlternate">{{
                        el.amount ? el.amount : 0
                      }}</view>
                    </view>
                    <view class="harvestName fw-400">{{ el.name }} </view>
                  </view>
                </view>
              </view>
            </view>
            <view
              class="walletList borRadius-19 bg-white mt-17 flex justify-between align-center"
            >
              <view
                class="harvest borRadius-19 flex bg-white justify-between w-full special"
              >
                <view
                  class="frame flex flex-column"
                  :class="idx === 2 ? 'justify-center' : ''"
                  v-for="(el, idx) in dailyList"
                  @click="goShareCode(el)"
                  :key="idx"
                >
                  <view class="frameLine" v-if="idx !== 2"></view>
                  <view class="digitList flex justify-center">
                    <view
                      class="digit dinAlternate"
                      :class="idx === 2 ? 'col-F3A' : ''"
                    >
                      {{ el.amount ? el.amount : idx !== 2 ? 0 : "" }}
                      <image
                        v-if="idx === 2 && el.amount"
                        src="https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/riseer.png"
                        class="imgaer"
                        mode="scaleToFill"
                      />
                    </view>
                  </view>
                  <view
                    class="harvestName fw-400"
                    :class="idx === 2 ? 'col-C7B fs-32' : ''"
                    >{{ el.name }}
                  </view>
                </view>
              </view>
            </view>
            <view class="order-wrapper borRadius-19 tui-skeleton-rect mt-17">
              <view class="order-bd">
                <block v-for="(item, index) in navList" :key="index">
                  <view class="order-item" @click="listTap(item)">
                    <image
                      :src="item.active ? item.activeImg : item.img"
                      :class="item.className"
                      mode="scaleToFill"
                    />
                    <view
                      class="txt tui-skeleton-rect"
                      :class="item.active ? 'col-F3A' : ''"
                      >{{ item.name }}</view
                    >
                  </view>
                </block>
              </view>
            </view>
            <view v-if="rewardList.length">
              <minCard
                :status="mark"
                :timeStatus="true"
                :items="item"
                v-for="(item, index) in rewardList"
                :key="index"
              ></minCard>
            </view>
            <emptyPage
              v-else
              :mTop="'5%'"
              title="暂无数据"
              :locate="true"
              :imgSrc="'https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/piteras.png'"
            ></emptyPage>
          </view>
        </scroll-view>
      </view>
    </view>
    <view
      class="footer flex justify-center align-center"
      v-if="!hasMore && rewardList.length !== 0"
    >
      <view class="no-more">{{ loadTitle }}</view>
    </view>
    <shareCode ref="shareCode"></shareCode>
  </view>
</template>
<script>
import navBar from "@/components/navBar";
import {
  userCenterInfo,
  getBillList,
  userFansData,
  userJuniorOrders,
  userManagerOrders,
  getSalesVolume,
} from "@/api/user.js";
import { Debounce } from "@/utils/validate.js";
import emptyPage from "@/components/emptyPage.vue";
import { mapGetters } from "vuex";
import minCard from "@/components/minCard";
import { getPointsData, getOrderCount } from "@/api/order.js";
import shareCode from "./shareCode.vue";
let publicUrl =
  "https://app-cangshu.oss-rg-china-mainland.aliyuncs.com/asssets/img/";
export default {
  computed: mapGetters(["isLogin", "uid", "globalData", , "isEmployee"]),
  components: {
    minCard,
    navBar,
    emptyPage,
    shareCode,
  },
  data() {
    return {
      title: "分享仓鼠",
      backgroundColor: "#fff",
      theme: "theme1",
      hasMore: true, // 是否还有更多数据
      loadTitle: "没有更多数据了",
      page: 1, // 页码
      showSkeleton: true, //骨架屏显示隐藏
      harvestList: [
        { name: "抵用券", amount: 0 },
        { name: "我的累计订单", amount: 0 },
        { name: "累计粉丝", amount: 0 },
      ],
      dailyList: [
        // { name: "今日粉丝订单", amount: "" },
        { name: "今日粉丝", amount: "" },
        { name: "累计销售额(元)", amount: "" },
        { name: "海报推广", amount: "" },
      ],
      navList: [
        {
          name: "奖励明细",
          img: publicUrl + "medaler.png",
          activeImg: publicUrl + "medalerActive.png",
          status: 1,
          className: "iconfont1",
          active: true,
        },
        {
          name: "我的粉丝",
          img: publicUrl + "hearter.png",
          activeImg: publicUrl + "hearterActive.png",
          status: 2,
          className: "iconfont2",
          active: false,
        },
        {
          name: "我的邀请人",
          img: publicUrl + "contactser.png",
          activeImg: publicUrl + "contactserActive.png",
          status: 4,
          className: "iconfont4",
          active: false,
        },
      ],
      rewardList: [], // 奖励数据
      mark: 1, // 标记看是点击了那些tab
      userInfo: {},
      isPageActive: true, // 标记页面是否激活
    };
  },
  onLoad() {
    setTimeout(() => {
      uni.setNavigationBarColor({
        frontColor: "#000000",
        backgroundColor: "#ffffff",
      });
    }, 300);
    this.rewardList = [];
    this.getUserCenterInfo();
    this.getOrderCountData();
  },
  onHide() {
    this.isPageActive = false; // 页面卸载时标记为未激活
  },
  onReachBottom() {
    // 触底加载更多
    if (!this.hasMore && this.isPageActive) return;
    this.getPayList();
  },
  methods: {
    // 订单状态总数
    getOrderCountData() {
      let data = {
        keywords: "",
        secondType: 0,
        status: "ALL",
      };
      getOrderCount(data).then((res) => {
        this.harvestList[1].amount = res.data;
      });
    },
    // 获取用户累计销售额
    getSalesVolumeData(id) {
      getSalesVolume(id).then((res) => {
        if (res.data.length) {
          // let str = this.computedTableData(res.data);
          let str = res.data[0].turnover == -1 ? 0 : res.data[0].turnover;
          if (str)
            this.dailyList[1].amount = Math.trunc(Number(str) * 100) / 100;
        }
      });
    },
    computedTableData(data) {
      let str = 0;
      data.forEach((item) => {
        if (item.turnover == -1) {
          item.turnover = 0;
        }
        if (item.points == -1) {
          item.points = 0;
        } // 初始化当前节点的总值（包含自身）
        item.allturnover = Number(item.turnover) * 100 || 0;
        item.allintegral = Number(item.points) * 100 || 0;
        item.subsetLength = 0; // 如果有子节点，递归计算所有下级节点的值
        if (item.subset.length > 0) {
          this.computedTableData(item.subset); // 递归处理子节点 // 过滤掉 isEstablish == 0 的子节点

          const validSubset = item.subset.filter(
            (child) => child.isEstablish !== 0
          ); // 计算有效子节点数量（包括它们的下级）
          item.subsetLength = validSubset.reduce(
            (sum, child) => sum + (child.subsetLength || 0) + 1, // +1 代表直接子节点
            0
          ); // 累加有效子节点的值

          item.allturnover += validSubset.reduce(
            (sum, child) => sum + (child.allturnover * 100 || 0),
            0
          );

          item.allintegral += validSubset.reduce(
            (sum, child) => sum + (child.allintegral * 100 || 0),
            0
          );
        }
        item.allturnover = item.allturnover / 100;
        item.allintegral = item.allintegral / 100;
        str += item.allturnover;
      });
      return str;
    },
    /**
     *  发现列表滑动中用到的方法
     */
    onScroll() {
      uni.$emit("scroll");
    },
    listTap(data) {
      if (!data.active) {
        this.navList.forEach((item) => {
          if (item.name === data.name) {
            this.mark = item.status;
            item.active = true;
            this.hasMore = true;
            this.rewardList = [];
            this.page = 1;
            this.getPayList();
          } else item.active = false;
        });
      }
    },
    /**
     *
     * 获取个人中心详情
     */
    getUserCenterInfo: function () {
      let that = this;
      userCenterInfo()
        .then((res) => {
          let data = res.data;
          this.userInfo = data;
          this.harvestList[0].amount = data.voucher;
          this.getData();
          this.getPayList();
          this.getSalesVolumeData(that.$store.state.app.uid);
          this.$store.commit("SETUID", data.id);
          this.$store.commit("SetIsEmployee", data.isEmployee);
          this.$store.commit("UPDATE_USERINFO", {
            avatar: data.avatar,
            nikeName: data.nickname,
            phone: data.phone,
            voucher: data.voucher,
            code: data.code,
            icode: data.icode,
            identityName: data.identityName,
            identity: data.identity,
          });
          this.$store.commit("LOGIN", {
            token: data.loginResponse.token,
          });

          this.showSkeleton = false;
        })
        .catch((err) => {
          this.showSkeleton = false;
        });
    },
    // 奖励明细
    getPayList: Debounce(function () {
      // uni.showToast({
      //   title: "加载中...", // 提示内容
      //   icon: "loading", // 图标类型，可选值：'success'、'loading'、'none'
      //   duration: 300, // 提示持续时间，单位毫秒
      //   mask: true, // 是否显示透明蒙层
      // });
      let data = {
        page: this.page,
        limit: 10,
        type: "1,3",
        flowingWaterType: "order",
      };
      let arr = [];
      if (this.mark === 1) {
        // 奖励明细
        getBillList(data).then((res) => {
          if (res.code === 200) {
            this.page++;
            let list = res.data.list ? res.data.list : [];
            list.forEach((item, id) => {
              item.list.forEach((e) => {
                arr.push(e);
              });
            });
            this.rewardList = this.rewardList.concat(arr); // 滚动添加之前的数据
            let status = list.length === 0 ? false : true;
            // status为true就是说明还有接口还有数据返回
            if (status) this.hasMore = true;
            else this.hasMore = false;
            // 模拟加载完成
            setTimeout(() => {
              uni.hideToast(); // 隐藏 Toast
            }, 300);
          }
        });
      } else if (this.mark === 2 || this.mark === 3) {
        // 我的粉丝
        let data = {
          page: this.page,
          limit: 10,
        };
        let event = "";
        if (this.mark === 2) event = userFansData(data);
        else if (this.mark === 3) event = userJuniorOrders(data);
        else if (this.mark === 4) event = userManagerOrders(data);
        event.then((res) => {
          if (res.code === 200) {
            this.page++;
            let list = res.data.list;
            if (this.mark === 3) {
              list = res.data.list.map((item) => {
                let str = item;
                str.remark = `@${item.user.phone}购买`;
                item.merchantOrderList[0].orderInfoList.forEach((e, index) => {
                  str.remark =
                    str.remark + (index !== 0 ? +"、" : "") + e.productName;
                });
                str.amount = item.productPrice;
                return str;
              });
            }
            this.rewardList = this.rewardList.concat(list);
            let status = list.length === 0 || list.length < 10 ? false : true;
            // status为true就是说明还有接口还有数据返回
            if (status) this.hasMore = true;
            else this.hasMore = false;
            // 模拟加载完成
            setTimeout(() => {
              uni.hideToast(); // 隐藏 Toast
            }, 300);
          }
        });
      } else if (this.mark === 4) {
        userManagerOrders({
          page: 1,
          limit: 10,
        }).then((res) => {
          if (res.code === 200) {
            let data = Object.keys(res.data).length ? res.data : {};
            this.rewardList = [];
            if (Object.keys(res.data).length) this.rewardList.push(data);
            if (data.id == -1) this.rewardList = [];
            this.hasMore = false;
            setTimeout(() => {
              uni.hideToast(); // 隐藏 Toast
            }, 300);
          }
        });
      }
      this.isPageActive = true;
    }),
    // 海报跳转
    goShareCode(data) {
      if (data.name === "海报推广")
        if (this.isLogin) {
          // uni.navigateTo({
          //   url: "/pages/shareCode/index",
          // });
          this.$refs.shareCode.open();
        }
      // uni.navigateTo({
      //   url: "/pages/userRegister/index",
      // });
    },
    // 获取订单数据
    getData() {
      getPointsData().then((res) => {
        // 订单统计
        // this.harvestList[1].amount = res.data.assembleCount;
        this.harvestList[2].amount = res.data.fansCount;
        // this.dailyList[0].amount = res.data.todayCount;
        // this.dailyList[0].amount = res.data.assembleCount;
        // this.harvestList[1].amount = res.data.todayCount
        //   ? res.data.todayCount
        //   : res.data.todayCount;
        this.dailyList[0].amount = res.data.toDayFansCount;
      });
    },
    // 微信分享；
    setOpenShare: function () {
      let that = this;
      if (that.$wechat.isWeixin()) {
        let configAppMessage = {
          desc: "crmeb",
          title: "crmeb",
          link: location.href,
          imgUrl: "",
        };
        that.$wechat.wechatEvevt(
          [
            "updateAppMessageShareData",
            "updateTimelineShareData",
            "onMenuShareAppMessage",
            "onMenuShareTimeline",
          ],
          configAppMessage
        );
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.svip-box {
  margin-top: 27.91rpx;
  .text {
    color: #ffd89c;
  }
}

.num-txt {
  font-size: 42rpx;
  color: #333333;
}
.mark-txt {
  padding: 6.23rpx 13.95rpx;
  border-radius: 17.44rpx;
  background: #534e5d;
  font-size: 17rpx;
  color: #f9ddc7;
}
page,
body {
  height: 100%;
  margin: 0;
}
.bg {
  width: 100%;
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.new-users {
  display: flex;
  flex-direction: column;
  height: 100%;
  .head {
    width: 100%;
    margin-top: 33.17rpx;
    .user-card {
      width: 100%;
      margin: 0 auto;
      .user-info {
        z-index: 20;
        display: flex;
        align-items: center;
        color: #fff;

        .avatar {
          width: 120rpx;
          height: 120rpx;
          border-radius: 50%;
        }
        .info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          margin-left: 26.16rpx;
          padding: 15rpx 0;

          .name {
            display: flex;
            align-items: center;
            font-size: 31rpx;
          }
          .num {
            display: flex;
            align-items: center;
            font-size: 26rpx;
            color: rgba(255, 255, 255, 0.6);

            image {
              width: 22rpx;
              height: 23rpx;
              margin-left: 20rpx;
            }
          }
        }
      }
    }
    .order-wrapper {
      background-color: #fff;
      padding: 47.9rpx 61rpx 0rpx 61rpx;
      position: relative;
      z-index: 11;
      .order-bd {
        display: flex;
        justify-content: space-between;
        padding-bottom: 29.65rpx;
        .order-item {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          .txt {
            margin-top: 15rpx;
            font-size: 24.42rpx;
            color: #272727;
          }
        }
      }
    }
  }
  .pic_status {
    width: 47.98rpx;
    height: 47.98rpx;
    background: #534e5d;
  }
}
.harvest {
  padding: 48.84rpx 28rpx 36.63rpx 28rpx;
  .frame {
    width: 33%;
    text-align: center;
    position: relative;
  }
  .frameLine {
    height: 64.53rpx;
    background: #f6f6f6;
    width: 2rpx;
    position: absolute;
    right: 0rpx;
    top: 50%;
    transform: translateY(-50%);
  }
  .digit {
    font-weight: bold;
    font-size: 52rpx;
    color: #272727;
  }
  .harvestName {
    font-size: 24rpx;
    color: #9a9999;
    margin-top: 12.21rpx;
  }
}
.walletList {
  height: 183.14rpx;
  .digit {
    position: relative;
  }
}
.special {
  padding: 38.37rpx 28rpx 36.37rpx 28rpx;
}
.col-F3A {
  color: #eb3f3a !important;
}
.col-C7B {
  margin-top: 0rpx !important;
  color: #11cc7b !important;
}

.imgaer {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  right: -30rpx;
  width: 25rpx;
  height: 17rpx;
}
.iconfont1 {
  width: 45.17rpx;
  height: 55.34rpx;
}
.iconfont2 {
  width: 51.89rpx;
  height: 50.71rpx;
}
.iconfont3 {
  width: 47.98rpx;
  height: 47.98rpx;
}
.iconfont4 {
  width: 56.34rpx;
  height: 47.98rpx;
}
.fs-32 {
  font-size: 30rpx !important;
}
</style>
